<?php
/**
 * ImpSoft Authentication Controller
 * All user login/logout shit goes in this controller
 * 
 * @package ImpSoft
 * @subpackage ImpSoft Models
 * @copyright Luke Visinoni (luke.visinoni@gmail.com)
 * @author Luke Visinoni (luke.visinoni@gmail.com)
 * @license GNU Lesser General Public License
 */
class AuthController extends ImpSoft_Controller_Action {

	public function init() {
	
		parent::init();
		$this->usrTab = new User;
	
	}
	/**
	 * Login Action
	 */
	public function loginAction() {
	
		$post = array();
		$errors = array();
		if ($this->isPost()) {
			$post = $this->getPost();
			$rules = with(new Q_Rule_Set())
				->add(new Q_Rule_NotNull(), array('username', 'password'), array('You must enter a username', 'You must enter a password'));
			if ($rules->validate($post)) {
				// authenticate this fella...
                try {
                    $this->verifyLogin($post['username'], $post['password']);
                    // update users table to show user is logged in
                    $user = $this->usrTab->fetchRow($this->usrTab->select()->where('username = ?', $post['username']));
                    $user->last_login = new Zend_Db_Expr('NOW()');
                    $user->save();
					// dispatch login event
					// $this->getPluginManager()->dispatchEvent(new ImpSoft_Event_Login($user));
                    $this->flash('Well congratulations on the successful login!', 'success');
                    $this->goToRoute('home');
                } catch (ImpSoft_Exception_InvalidLogin $e) {
                    Zend_Auth::getInstance()->clearIdentity();
                    $this->flash($e->getMessage());
                    $this->goToRoute('auth_login');
				} catch (ImpSoft_Exception_AccountNotActive $e) {
                    Zend_Auth::getInstance()->clearIdentity();
                    $this->flash($e->getMessage());
                    $this->goToRoute('auth_login');
				} catch (ImpSoft_Event_Exception $e) {
                    Zend_Auth::getInstance()->clearIdentity();
                    $this->flash($e->getMessage());
                    $this->goToRoute('auth_login');
                } catch (Zend_Db_Exception $e) {
                    $this->flash("We are experiencing some technical difficulties at the moment. Please try again later.");
                    $this->goToRoute('auth_login');
                }
			} else {
				$errors = $rules->getErrors();
			}
		}
		$this->view->post = $post;
		$this->view->errors = $errors;
	
	}
	/**
     * Logout screen
     */
	public function logoutAction() {

	    if ($this->isLoggedIn()) {
	        Zend_Auth::getInstance()->clearIdentity();
			//$this->getPluginManager()->dispatchEvent(new ImpSoft_Plugin_Event_Logout());
	        $this->flash('You have been logged out, thanks for dropping by!', 'success');
	    } else {
            $this->flash('You cannot log out because you aren\'t logged in!');
	    }
	    $this->goToRoute('auth_login');

	}
    /**
     * Checks that user login / password are correct
     * @return Zend_Auth_Result object
     */
    protected function verifyLogin($username, $password) {
    
        $authAdapter = new Zend_Auth_Adapter_DbTable(
			$this->db,
			$this->usrTab->info('name'),
			'username',
			'password'
			/**
			 * TODO: Until I get pgcrypto working I just won't hash passwords
			 * "SHA1(salt || '$' || '" . $this->_config->secretKey . "$' || ?)" // adds the salt and pepper to the user's password and hashes it
			 */
		);
        $authAdapter->setIdentity($username)
                    ->setCredential($password);
        
        $result = $authAdapter->authenticate();
        if (!$result->isValid()) {
            throw new ImpSoft_Exception_InvalidLogin('Invalid username/password combination');
        } else {
	        // $userdata = $authAdapter->getResultRowObject(null, 'password');
	        // let's store an actual UserRow object
	        $userRow = $this->usrTab->fetchRow($this->usrTab->select()->where('username = ?', $username));
	        if ($userRow->is_active) {
		        Zend_Auth::getInstance()->getStorage()->write($userRow);
	        } else {
	        	throw new ImpSoft_Exception_AccountNotActive('Your account is not active yet. Please check your e-mail for your activation link.');
	        }
        }
    
    }

}